<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/view/include/taglib.jsp"%>
<html lang="cn" class="app">
<head>
    <title>后台管理 - 模板</title>
    <meta name="description" content="app, web app, responsive, admin dashboard, admin, flat, flat ui, ui kit, off screen nav" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <link rel="icon" type="image/png" href="icon.png">
    <link rel="apple-touch-icon-precomposed" href="icon.png">
    <link rel="stylesheet" href="${ctxStatic}/js/jPlayer/jplayer.flat.css" type="text/css" />
    <link rel="stylesheet" href="${ctxStatic}/css/bootstrap.css" type="text/css" />
    <link rel="stylesheet" href="${ctxStatic}/css/animate.css" type="text/css" />
    <link rel="stylesheet" href="${ctxStatic}/css/font-awesome.min.css" type="text/css" />
    <link rel="stylesheet" href="${ctxStatic}/css/simple-line-icons.css" type="text/css" />
    <link rel="stylesheet" href="${ctxStatic}/css/font.css" type="text/css" />
    <link rel="stylesheet" href="${ctxStatic}/css/app.css" type="text/css" />
    <link rel="stylesheet" href="${ctxStatic}/js/chosen/chosen.css" type="text/css" />
    <link rel="stylesheet" href="${ctxStatic}/js/ztree/css/zTreeStyle.css" />

    <link rel="stylesheet" href="${ctxStatic}/js/highlight/styles/default.css">
    <script src="${ctxStatic}/js/highlight/highlight.pack.js"></script>

    <!--[if lt IE 9]>
    <script src="${ctxStatic}/js/ie/html5shiv.js"></script>
    <script src="${ctxStatic}/js/ie/respond.min.js"></script>
    <script src="${ctxStatic}/js/ie/excanvas.js"></script>
    <![endif]-->
</head>
<body>

<section class="scrollable wrapper">
    <div class="row">
        <div class="col-lg-12">
            <!-- 引导开始 -->
            <ul class="breadcrumb">
                <li><a href="${ctx}/welcome"><i class="fa fa-home"></i> 主页</a></li>
                <li>代码生成</li>
                <li class="active">模板管理</li>
            </ul>
            <!-- 引导结束 -->

        </div>
    </div>
    <%--左边--%>
    <div class="col-sm-12 col-md-4" style="padding: 0px;">
        <%--树型目录--%>
        <div class="col-sm-12" style="padding: 0px;">
            <section class="panel panel-default">
                <header class="panel-heading font-bold">
                    项目目录结构
                    <select id="projectId" style="width:200px;margin-top:10px;" class="chosen-select">
                        <option value="">请选择项目</option>
                        <c:forEach items="${codeProjectlist}" var="project">
                            <option value="${project.id}">${project.name}</option>
                        </c:forEach>
                    </select>
                </header>
                <div class="panel-body">
                    <style>.line{height:auto;}</style><%--这个不能删除--%>
                    <ul id="tree" class="ztree"></ul><!-- 资源树 -->
                </div>
            </section>
        </div>

        <%--操作台--%>
        <div class="col-sm-12" style="padding: 0px;">
            <section class="panel panel-default">
                <header class="panel-heading font-bold">操作台</header>
                    <table class="table table-striped m-b-none">
                        <thead>
                        <tr>
                            <th class="text-center">节点标识</th>
                            <th class="text-center">节点名称</th>
                            <th class="text-center">选中项目</th>
                        </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="text-center" ><input type="text" id="chosenTreeValue" class="form-control" style="border: 0px;" readonly/></td>
                                <td class="text-center" ><input type="text" id="chosenTreeName" class="form-control" style="border: 0px;" readonly/></td>
                                <td class="text-center" ><input type="text" id="chosenProjectId" class="form-control" style="border: 0px;" readonly/></td>
                            </tr>
                            <tr>
                                <td class="text-center" ><button class="btn btn-sm btn-info" onclick="addCatalog()">新增目录</button></td>
                                <td class="text-center" ><button class="btn btn-sm btn-info" onclick="addTemplate()">新增模板</button></td>
                                <td class="text-center" ><button class="btn btn-sm btn-danger" onclick="deleteTreeNode()">删除节点</button></td>
                            </tr>
                            <%--<tr>--%>
                                <%--<td class="text-center" ><button class="btn btn-sm btn-info" onclick="createAll()">生成所有</button></td>--%>
                                <%--<td class="text-center" ><button class="btn btn-sm btn-info" onclick="createChoose()">生成选中</button></td>--%>
                                <%--<td class="text-center" ></td>--%>
                            <%--</tr>--%>
                        </tbody>
                    </table>
            </section>
        </div>

        <%--生成记录--%>
        <div class="col-sm-12" style="padding: 0px;">
            <section class="panel panel-default">
                <header class="panel-heading font-bold">生成记录</header>
                <table class="table table-striped m-b-none">
                    <thead>
                    <tr>
                        <th class="text-center">输出</th>
                        <th class="text-center">结果</th>
                        <th class="text-center">时间</th>
                    </tr>
                    </thead>
                    <tbody id="tplView">

                    </tbody>
                </table>
                <footer class="panel-footer">
                    <div class="row">
                        <%--分页--%>
                        <div id="page" class="col-sm-12 text-right text-center-xs"></div>
                    </div>
                </footer>
            </section>
        </div>


    </div>
    <div class="col-sm-12 col-md-8">
    <section class="panel panel-default">
        <%--操作区域 开始--%>
        <div class="row wrapper">
            <div class="col-sm-5 m-b-xs">
                <shiro:hasPermission name="code:codeTemplate:create">
                <button id="toEditBtn" class="btn btn-s-md btn-info" onclick="toEdit()">编辑</button>
                <button id="toSaveBtn" class="btn btn-s-md btn-info" onclick="toSave()" style="display: none;">保存</button>
                <button id="toBackBtn" class="btn btn-s-md btn-default" onclick="toBack()" style="display: none;">返回</button>
                </shiro:hasPermission>
            </div>
            <div class="col-sm-7 m-b-xs">

            </div>
        </div>
        <%--操作区域 结束--%>
        <section class="panel">
            <pre>
                <code class="java" id="templateContent"></code>
            </pre>
            <textarea id="templateEditContent" class="form-control" rows="5" style="display: none;min-height:400px;"></textarea>
        </section>

    </section>
    </div>
</section>

<script id="tplHtml" type="text/x-jquery-tmpl">
    {{if results && results.length>0 }}
        {{each results}}
        <tr>
            <td class="text-center">{{= outName}}</td>
            <td class="text-center">{{if result=="success"}}<span class="label label-success">成功</span>{{else}}<span class="label label-danger">失败</span>{{/if}}</td>
            <td class="text-center">{{= createDateStr}}</td>
        </tr>
        {{/each}}
    {{else}}
        <tr><td colspan="3" class="text-center" >暂无数据</td></tr>
    {{/if}}
</script>
</body>
<script src="${ctxStatic}/js/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="${ctxStatic}/js/bootstrap.js"></script>
<!-- App -->
<script src="${ctxStatic}/js/app.js"></script>
<script src="${ctxStatic}/js/slimscroll/jquery.slimscroll.min.js"></script>
<script src="${ctxStatic}/js/app.plugin.js"></script>
<script type="text/javascript" src="${ctxStatic}/js/jPlayer/jquery.jplayer.min.js"></script>
<script type="text/javascript" src="${ctxStatic}/js/jPlayer/add-on/jplayer.playlist.min.js"></script>
<script type="text/javascript" src="${ctxStatic}/js/jPlayer/demo.js"></script>
<script type="text/javascript" src="${ctxStatic}/js/tools.js"></script>
<script type="text/javascript" src="${ctxStatic}/js/page/paging.js"></script>
<script type="text/javascript" src="${ctxStatic}/js/layer/layer.js"></script>
<script type="text/javascript" src="${ctxStatic}/js/tmpl/jquery.tmpl.js"></script>

<script type="text/javascript" src="${ctxStatic}/js/chosen/chosen.jquery.min.js"></script>

<script src="${ctxStatic}/js/ztree/js/jquery.ztree.core-3.5.min.js"></script>
<%--<script id="tplHtml" type="text/x-jquery-tmpl">--%>
    <%--{{if results && results.length>0 }}--%>
        <%--{{each results}}--%>
        <%--<tr>--%>
            <%--<td class="text-center" >{{= ($index+1)+(pageNo-1)*10}}</td>--%>
                    <%--<td class="text-center">{{= id}}</td>--%>
                    <%--<td class="text-center">{{= projectId}}</td>--%>
                    <%--<td class="text-center">{{= catalog}}</td>--%>
                    <%--<td class="text-center">{{= name}}</td>--%>
                    <%--&lt;%&ndash;<td class="text-center">{{= content}}</td>&ndash;%&gt;--%>
                    <%--&lt;%&ndash;<td class="text-center">{{= sort}}</td>&ndash;%&gt;--%>
                    <%--&lt;%&ndash;<td class="text-center">{{= createBy}}</td>&ndash;%&gt;--%>
                    <%--&lt;%&ndash;<td class="text-center">{{= createDateStr}}</td>&ndash;%&gt;--%>
                    <%--&lt;%&ndash;<td class="text-center">{{= updateBy}}</td>&ndash;%&gt;--%>
                    <%--&lt;%&ndash;<td class="text-center">{{= updateDateStr}}</td>&ndash;%&gt;--%>
                    <%--&lt;%&ndash;<td class="text-center" >{{if status=="1"}}<span class="label label-success">有效</span>{{else}}<span class="label label-danger">无效</span>{{/if}}</td>&ndash;%&gt;--%>
                    <%--&lt;%&ndash;<td class="text-center">{{= remarks}}</td>&ndash;%&gt;--%>
                    <%--<td class="text-center">{{= startNum}}/{{= successNum}}/{{= failureNum}}</td>--%>
            <%--<td class="text-center">--%>
                <%--<div class="btn-group">--%>
                    <%--<a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-pencil"></i></a>--%>
                    <%--<ul class="dropdown-menu pull-right" style="min-width: 60px;">--%>
                        <%--<shiro:hasPermission name="code:codeTemplate:update">--%>
                        <%--<li><a href="javascript:;" onclick="openModel('','${ctx}/code/codeTemplate/update?id={{= id }}',true,true)">编辑</a></li>--%>
                        <%--</shiro:hasPermission>--%>
                        <%--<shiro:hasPermission name="code:codeTemplate:delete">--%>
                        <%--<li><a href="${ctx}/code/codeTemplate/delete?id={{= id }}&pageNo={{= pageNo}}&pageSize={{= pageSize}}" onclick="return confirm('确认要删除该条数据吗？', this.href)" title="删除">删除</a></li>--%>
                        <%--</shiro:hasPermission>--%>
                    <%--</ul>--%>
                <%--</div>--%>
            <%--</td>--%>
        <%--</tr>--%>
        <%--{{/each}}--%>
    <%--{{else}}--%>
        <%--<tr><td colspan="7" class="text-center" >暂无数据</td></tr>--%>
    <%--{{/if}}--%>
<%--</script>--%>
<script>
    $(function(){
        var msg = '${msg}';
        if(msg!=''){
            showMsg(msg);
        }

        /**
         * 1、加载项目列表
         * 2、加载目录
         * 3、加载模板内容
         */
        loadCatalog("");//加载目录

        /** 绑定项目选择事件 */
        $("#projectId").chosen().on("change", function (evt, params) {
            //清空相关数据
            resetChosenData();

            $("#chosenProjectId").val(params.selected);
            loadCatalog(params.selected);//加载目录
            loadRecord(params.selected);//加载记录
        });

    })

    /** 加载目录 */
    function loadCatalog(projectId){
       if(projectId==""){
            $("#tree").html("请先选择项目");
       }else{
            var loadingLayer = layer.load(1, {shade: [0.1,'#fff']});//loading
            //根据项目标识获取目录
            $.ajax({
               type: 'post',
               url: '${ctx}/code/codeCatalog/getCatalogAndTemplateList.json?timeStamp='+new Date().getTime(),
               dataType:"json",
               data: {"projectId":projectId},
               success: function (data) {
                   layer.close(loadingLayer);
                   var catalogList = data.data.codeCatalogList;
                   var templateList = data.data.codeTemplateList;
                   var setting = {
                       view: {
                           dblClickExpand: false
                       },
                       check: {
                           enable: true
                       },
                       data: {
                           simpleData: {
                               enable: true
                           }
                       },
                       callback : {
                           onClick : function(event, treeId, treeNode) {
                               <%--location.href = "${ctx}/resource?id="+treeNode.id;--%>
                               var nodeId = treeNode.id;//树节点ID
                               if(nodeId.indexOf("T")==0){
                                   var templateId = nodeId.substr(1,nodeId.length)
                                   //模板节点,加载指定模板内容
                                   loadTemplate(templateId);
                               }
                               $("#chosenTreeValue").val(treeNode.id);
                               $("#chosenTreeName").val(treeNode.name);

                               resetRight();
                           }
                       }
                   };
                   var zNodesHtml = "";
                   for(var i=0;i<catalogList.length;i++){
                       zNodesHtml += ",{id:'"+catalogList[i].id+"', pId: '"+catalogList[i].parentId+"', name: '"+catalogList[i].name+"', open:1,icon:'${ctxStatic}/js/ztree/img/file.png'}";
                   }
                   for(var i=0;i<templateList.length;i++){
                       zNodesHtml += ",{id:'T"+templateList[i].id+"', pId: '"+templateList[i].catalog+"', name: '"+templateList[i].name+"', open:1}";
                   }

                   if(zNodesHtml.startsWith(",")){
                       zNodesHtml = zNodesHtml.substr(1,zNodesHtml.length);
                   }

                   zNodesHtml = "[" + zNodesHtml + "]";

                   var zNodes = eval(zNodesHtml);

                   var ztree = $.fn.zTree.init($("#tree"), setting, zNodes);
                   ztree.expandAll(true);
               },error:function(){
                   layer.close(loadingLayer);
                   alert("程序异常");
                }
            });





       }
    }

    /** 加载模板内容 */
    function loadTemplate(templateId){
        if(templateId!=""){
            var loadingLayer = layer.load(1, {shade: [0.1,'#fff']});//loading
            $.ajax({
                type: 'post',
                url: '${ctx}/code/codeTemplate/get.json?timeStamp='+new Date().getTime(),
                dataType:"json",
                data: {"id":templateId},
                success: function (data) {
//                    console.info(data)
                    layer.close(loadingLayer);
                    var codeTemplate = data.data;
                    var templateContent = codeTemplate.content;
                    $("#templateEditContent").html(templateContent);
                    $("#templateContent").html(templateContent);
                    //$("#templateContent").parent().show();

                    $('pre code').each(function(i, block) {
                        hljs.highlightBlock(block);
                    });
                },error:function(){
                    layer.close(loadingLayer);
                    alert("程序异常");
                }
            });
        }
    }

    /**加载生成记录*/
    function loadRecord(projectId){
        $.ajax({
            type: 'post',
            url: '${ctx}/code/codeRecord/getPage.json',
            dataType:"json",
            data: {"projectId":projectId},
            success: function (data) {
                var page = data.data;
                $( "#tplView" ).empty();
                $( "#tplHtml" ).tmpl( data.data ).appendTo( "#tplView" );

                //分页
                $("#page").paging({
                    pageNo:page.pageNo,
                    totalPage: page.totalPage,
                    totalSize: page.totalRecord,
                    callback: function(num) {
                        searchPage(num);
                    }
                })

            }
        });
    }



    /**进入编辑*/
    function toEdit(){
        //隐藏编辑，显示保存
        $("#toEditBtn").hide();
        $("#toSaveBtn").show();
        $("#toBackBtn").show();

        $("#templateContent").parent().hide();
        $("#templateEditContent").show();

        //让textarea自适应高度
        $('textarea').each(function () {
            this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
        }).on('input', function () {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });
    }

    /**执行保存*/
    function toSave(){
        //获取当前选择的目录或模板ID
        var chosenTreeValue = $("#chosenTreeValue").val();

        if(chosenTreeValue.indexOf("T") != 0) {
            alert("丢失模板标识（请重新选择模板进行编辑）");
            return false;
        }
        var templateId = chosenTreeValue.substr(1, chosenTreeValue.length);
        //执行保存
        var loadingLayer = layer.load(1, {shade: [0.1,'#fff']});//loading

        $.ajax({
            type: 'post',
            url: '${ctx}/code/codeTemplate/update.json?timeStamp='+new Date().getTime(),
            dataType:"json",
            data: {"id":templateId,"content":$("#templateEditContent").val()},
            success: function (data) {
                layer.close(loadingLayer);
                layer.msg('成功修改模板：'+$("#chosenTreeName").val());

                //隐藏保存，显示编辑
                resetRight();

                //重新加载模板内容
                loadTemplate(templateId);
            },error:function(){
                layer.close(loadingLayer);
                layer.msg('程序异常');
            }
        });

    }
    /**撤回*/
    function toBack(){
        //隐藏保存，显示编辑
        resetRight();

        //重新加载模板内容（为了安全）
        loadTemplate($("#chosenTreeValue").val());
    }

    /**新增目录*/
    function addCatalog(){
        if($("#chosenProjectId").val()==""){
            alert("请先选择项目！");
            return false;
        }
        var chosenTreeValue = $("#chosenTreeValue").val();//选择的节点ID
        if(chosenTreeValue.indexOf("T")==0){
            //选择的是模板，模板不能有下级节点
            alert("请选择目录（请勿选择模板）");
            return false;
        }
        var titleTip = '';
        if($("#chosenTreeValue").val()==""){
            titleTip = '新建顶级目录';
        }else{
            titleTip = '在【'+$("#chosenTreeName").val()+'(ID='+$("#chosenTreeValue").val()+')】下新建目录';
        }
        layer.prompt({title:titleTip , formType: 3}, function(text, index){
            layer.close(index);
            var loadingLayer = layer.load(1, {shade: [0.1,'#fff']});//loading
            $.ajax({
                type: 'post',
                url: '${ctx}/code/codeCatalog/create.json?timeStamp='+new Date().getTime(),
                dataType:"json",
                data: {"parentId":$("#chosenTreeValue").val(),"name":text,"projectId":$("#chosenProjectId").val()},
                success: function (data) {
                    layer.close(loadingLayer);
                    layer.msg('成功新建：'+text);
                    loadCatalog($("#chosenProjectId").val());
                },error:function(){
                    layer.close(loadingLayer);
                    layer.msg('程序异常');
                }
            });

        });
    }

    /**新增模板*/
    function addTemplate(){
        if($("#chosenProjectId").val()==""){
            alert("请先选择项目！");
            return false;
        }
        var chosenTreeValue = $("#chosenTreeValue").val();//选择的节点ID
        if(chosenTreeValue.indexOf("T")==0){
            //选择的是模板，模板不能有下级节点
            alert("请选择目录（请勿选择模板）");
            return false;
        }
        var titleTip = '';
        if($("#chosenTreeValue").val()==""){
            alert("请先创建或选择目录！");
        }else{
            titleTip = '在【'+$("#chosenTreeName").val()+'(ID='+$("#chosenTreeValue").val()+')】下新建模板文件';
            layer.prompt({title:titleTip , formType: 3}, function(text, index){
                layer.close(index);
                var loadingLayer = layer.load(1, {shade: [0.1,'#fff']});//loading
                $.ajax({
                    type: 'post',
                    url: '${ctx}/code/codeTemplate/create.json?timeStamp='+new Date().getTime(),
                    dataType:"json",
                    data: {"catalog":$("#chosenTreeValue").val(),"name":text,"projectId":$("#chosenProjectId").val()},
                    success: function (data) {
                        layer.close(loadingLayer);
                        layer.msg('成功新建：'+text);
                        loadCatalog($("#chosenProjectId").val());
                    },error:function(){
                        layer.close(loadingLayer);
                        layer.msg('程序异常');
                    }
                });

            });
        }
    }

    /**删除模板*/
    function deleteTreeNode(){
        //获取当前选择的目录或模板ID
        var chosenTreeValue = $("#chosenTreeValue").val();
        var chosenTreeName = $("#chosenTreeName").val();
        if(chosenTreeValue==""){
            alert("请先选择需要删除的目录或模板！");
            return false;
        }
        if(confirm("是否确认删除【"+chosenTreeName+"】")){
            if(chosenTreeValue.indexOf("T")==0){
                var id = chosenTreeValue.substr(1,chosenTreeValue.length);
                var loadingLayer = layer.load(1, {shade: [0.1,'#fff']});//loading
                //这是模板
                $.ajax({
                    type: 'post',
                    url: '${ctx}/code/codeTemplate/delete.json?timeStamp='+new Date().getTime(),
                    dataType:"json",
                    data: {"id":id},
                    success: function (data) {
                        layer.close(loadingLayer);
                        layer.msg('成功删除：'+chosenTreeName);
                        loadCatalog($("#chosenProjectId").val());
                    },error:function(){
                        layer.close(loadingLayer);
                        layer.msg('程序异常');
                    }
                });
            }else{
                //这是目录
                var id = chosenTreeValue;
                var loadingLayer = layer.load(1, {shade: [0.1,'#fff']});//loading
                //这是模板
                $.ajax({
                    type: 'post',
                    url: '${ctx}/code/codeCatalog/delete.json?timeStamp='+new Date().getTime(),
                    dataType:"json",
                    data: {"id":id},
                    success: function (data) {
                        layer.close(loadingLayer);
                        if(data.ret==1){
                            layer.msg('成功删除：'+chosenTreeName);
                            loadCatalog($("#chosenProjectId").val());
                        }else{
                            layer.msg(data.msg);
//                            loadCatalog($("#chosenProjectId").val());
                        }
                    },error:function(){
                        layer.close(loadingLayer);
                        layer.msg('程序异常');
                    }
                });
            }
        }
    }
    <%--/**生成项目所有模板*/--%>
    <%--function createAll(){--%>

    <%--}--%>
    <%--/**生成选择的指定模板*/--%>
    <%--function createChoose(){--%>
        <%--//必须先选择项目--%>
        <%--if($("#chosenProjectId").val()==""){--%>
            <%--alert("请先选择项目！");--%>
            <%--return false;--%>
        <%--}--%>
        <%--//再选择模板--%>
        <%--var chosenTreeValue = $("#chosenTreeValue").val();//选择的节点ID,即模板标识--%>
        <%--if(chosenTreeValue.indexOf("T")!=0){--%>
            <%--alert("请选择模板");--%>
            <%--return false;--%>
        <%--}--%>
        <%--var templateId = chosenTreeValue.substr(1,chosenTreeValue.length);--%>

        <%--//生成模板文件--%>
        <%--$.ajax({--%>
            <%--type: 'post',--%>
            <%--url: '${ctx}/code/codeTemplate/startOne.json?timeStamp='+new Date().getTime(),--%>
            <%--dataType:"json",--%>
            <%--data: {"templateId":templateId},--%>
            <%--success: function (data) {--%>
                <%--layer.close(loadingLayer);--%>
                <%--if(data.ret==1){--%>
                    <%--layer.msg('成功删除：'+chosenTreeName);--%>
                    <%--loadCatalog($("#chosenProjectId").val());--%>
                <%--}else{--%>
                    <%--layer.msg(data.msg);--%>
<%--//                            loadCatalog($("#chosenProjectId").val());--%>
                <%--}--%>
            <%--},error:function(){--%>
                <%--layer.close(loadingLayer);--%>
                <%--layer.msg('程序异常');--%>
            <%--}--%>
        <%--});--%>

    <%--}--%>

    /** 清除选择的相关数据 */
    function resetChosenData(){
        $("#chosenTreeValue").val("");
        $("#chosenTreeName").val("");
        $("#chosenProjectId").val("");
    }
    /**相当于初始化右边的按钮显示*/
    function resetRight() {
        //隐藏保存，显示编辑
        $("#toSaveBtn").hide();
        $("#toBackBtn").hide();
        $("#toEditBtn").show();

        $("#templateEditContent").hide();
        $("#templateContent").parent().show();

    }
</script>
</html>
